package xiaobange.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import xiaobange.common.R;
import xiaobange.dto.DishDto;
import xiaobange.entity.Category;
import xiaobange.entity.Dish;
import xiaobange.entity.DishFlavor;
import xiaobange.service.CategoryService;
import xiaobange.service.DishFlavorService;
import xiaobange.service.DishService;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping
    public R<String> DishAdd(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> DishPage(int page,int pageSize,String name){
        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //设置查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null ,Dish::getName,name);
        lambdaQueryWrapper.orderByDesc(Dish::getCreateTime);
        //执行查询
        dishService.page(dishPage,lambdaQueryWrapper);
        //对象拷贝，并且忽略records属性
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //取出查询到的数据
        List<Dish> records = dishPage.getRecords();
        //拿到菜品分类表的菜品分类名称
        List<DishDto> dtoList = records.stream().map( (item) ->{
            //拿到菜品对呀的ID
            Long categoryId = item.getCategoryId();
            //根据查询相关菜品
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            //把查询到的菜品名称赋给实体类
            DishDto dishDto = new DishDto();
            //因为实体类是new出来的所以对它进行一个拷贝
            BeanUtils.copyProperties(item,dishDto);
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());//将结果转成一个集合
        //给菜品分类名称复制
        dishDtoPage.setRecords(dtoList);
        return R.success(dishDtoPage);
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> DeleteIds(Long[] ids){
        dishService.DeleteIds(ids);
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }

    /**
     * 修改状态
     * @param State
     * @param ids
     * @return
     */

    @PostMapping("/status/{State}")
    public R<String> UpdateState(@PathVariable int State,Long[] ids){
        dishService.UpdateStatus(State,ids);
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);
        return R.success("操作成功");
    }


    /**
     * 修改菜品回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> Update(@PathVariable Long id){
        DishDto updateData = dishService.UpdateDataShow(id);
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);
        return R.success(updateData);
    }

    @PutMapping
    public R<String> UpdateOK(@RequestBody DishDto dishDto){
        dishService.UpdateSubmit(dishDto);
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }


    /**
     * 套餐管理新增页面，套餐菜品请求
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> DishNameList(Dish dish){
        List<DishDto> collect = null;
        //设置key
        String key = "Dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        collect = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //判断Redis中是否有缓存数据
        if (collect != null){
            return R.success(collect);
        }
        //设置条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId,dish.getCategoryId());
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(lambdaQueryWrapper);

        collect = list.stream().map((data) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(data, dto);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(data.getId() != null, DishFlavor::getDishId, data.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dto.setFlavors(dishFlavors);
            return dto;
        }).collect(Collectors.toList());
        //将数据存到Redis中,过期时间30分钟
        redisTemplate.opsForValue().set(key,collect,30, TimeUnit.MINUTES);
        return R.success(collect);
    }

}
